// waterfall.js
function waterFallLayout(parentId, childClassName) {
  const cParent = document.getElementById(parentId);
  const cChild = cParent.getElementsByClassName(childClassName);
  const screenWidth = parentId.innerWidth;
  const imgWidth = childClassName.offsetWidth || 0;
  const num = Math.floor(screenWidth / imgWidth);
  cParent.style.width = `${imgWidth * num}px`;

  // 操作第 num+1 张
  const boxHeightArr = [];
  for (let i = 0; i < cChild.length; i++) {
    if (i < 2) {  // 第一行
      boxHeightArr.push(cChild[i].offsetHeight);
    } else {
      // 找数组最小值
      const minHeight = Math.min(...boxHeightArr);
      const minIndex = boxHeightArr.indexOf(minHeight);

      // 摆放图片
      cChild[i].style.position = 'absolute';
      cChild[i].style.top = `${minHeight}px`;
      cChild[i].style.left = `${cChild[minIndex].offsetLeft}px`;

      // 更新这一列的高度
      boxHeightArr[minIndex] = boxHeightArr[minIndex] + cChild[i].offsetHeight;
    }
  }
}

export default waterFallLayout;